package com.rbac.admin.service.system.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rbac.admin.entity.system.SystemRole;
import com.rbac.admin.mapper.system.RoleMapper;
import com.rbac.admin.mapper.system.UserRoleMapper;
import com.rbac.admin.service.system.RoleService;
import com.rbac.admin.vo.system.RoleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 角色服务实现类
 *
 * @author rbac-admin
 * @since 2024-07-18
 */
@Slf4j
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, SystemRole> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public List<SystemRole> getRolesByUserId(String userId) {
        return roleMapper.selectRolesByUserId(userId);
    }

    @Override
    public SystemRole getRoleByCode(String code) {
        return roleMapper.selectByRoleCode(code);
    }
    
    @Override
    public IPage<RoleVO> getRolePage(Page<RoleVO> page, SystemRole role) {
        return roleMapper.selectRolePage(page, role);
    }
    
    @Override
    public RoleVO getRoleById(String roleId) {
        return roleMapper.selectRoleById(roleId);
    }
    
    @Override
    public List<RoleVO> getAllActiveRoles() {
        return roleMapper.selectAllActiveRoles();
    }
    
    @Override
    public boolean checkRoleCodeExists(String roleCode, String excludeRoleId) {
        if (roleCode == null || roleCode.isEmpty()) {
            return false;
        }
        Integer count = roleMapper.checkRoleCodeExists(roleCode, excludeRoleId);
        return count != null && count > 0;
    }
    
    @Override
    public boolean checkRoleNameExists(String roleName, String excludeRoleId) {
        if (roleName == null || roleName.isEmpty()) {
            return false;
        }
        Integer count = roleMapper.checkRoleNameExists(roleName, excludeRoleId);
        return count != null && count > 0;
    }
    
    @Override
    public boolean hasAssociatedUsers(String roleId) {
        if (roleId == null || roleId.isEmpty()) {
            return false;
        }
        // 查询与该角色关联的用户
        List<String> userIds = userRoleMapper.selectUserIdsByRoleId(roleId);
        // 如果有关联用户，返回true
        return userIds != null && !userIds.isEmpty();
    }
} 